package com.java.common.boot.validator;

import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.java.common.lang.annotation.validator.Mobile;
import com.java.common.utils.StringUtils;

/**
 * 手机号验证实现
 * 
 * @author yilabao
 * @date 2021年3月4日
 * 
 * @see Mobile
 */
public class MobileValidator implements ConstraintValidator<Mobile, String> {

    private boolean required;

    private final String MOBILE_REGEXP = "^[1][3,4,5,6,7,8,9][0-9]{9}$";

    @Override
    public void initialize(Mobile constraintAnnotation) {
        this.required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isNotEmpty(value)) {
            return Pattern.matches(MOBILE_REGEXP, value);
        }
        return !this.required;
    }

}
